package com.sdruixinggroup.mondayb2b.ui;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ProgressBar;

import com.bumptech.glide.Glide;
import com.google.gson.reflect.TypeToken;
import com.sdruixinggroup.mondayb2b.API.API;
import com.sdruixinggroup.mondayb2b.R;
import com.sdruixinggroup.mondayb2b.interfaces.ObjectCallBack;
import com.sdruixinggroup.mondayb2b.models.Address;
import com.sdruixinggroup.mondayb2b.models.Province;
import com.sdruixinggroup.mondayb2b.models.ShareInformation;
import com.sdruixinggroup.mondayb2b.ui.Activities.AddressActivity;
import com.sdruixinggroup.mondayb2b.ui.Activities.BasicMapActivity;
import com.sdruixinggroup.mondayb2b.ui.Activities.CityListActivity;
import com.sdruixinggroup.mondayb2b.ui.Activities.EditOrderFormActivity;
import com.sdruixinggroup.mondayb2b.ui.Activities.LoginActivity;
import com.sdruixinggroup.mondayb2b.ui.Activities.ShoppingCartActivity;
import com.sdruixinggroup.mondayb2b.utils.UserInfoUtil;
import com.sdruixinggroup.mondayb2b.wxapi.WXEntryUtil;
import com.tencent.connect.common.Constants;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.ExecutionException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;
import okhttp3.Call;

import static com.sdruixinggroup.mondayb2b.API.Constants.QQ_APP_ID;
import static com.sdruixinggroup.mondayb2b.ui.MineDetailActivity.compressBySizeHeight;
import static com.sdruixinggroup.mondayb2b.ui.MineDetailActivity.compressBySizeWidth;
import static com.sdruixinggroup.mondayb2b.ui.fragments.EditOrderFormFragment.KEY_QUICK_ORDER;


/**
 * webview界面
 * <p>
 * Created by czhang on 16/7/8.
 */
public class WebActivity extends BaseActivity implements IUiListener,MainActivity.OnTabActivityResultListener {
    //http://h5.ldnz.ydd100.cn
    //private final static String H5_SERVER_URL = "http://h5.ldnz.ydd100.cn/#/";
    private final static String H5_SERVER_URL = "http://h5.member.ldnz.rxjt.co/#/";

    public static final String INTENT_EXTRA_BEGIN_URL = "beginUrl";
    @BindView(R.id.bt_test)
    Button btTest;
    private String token;

    @BindView(R.id.webView)
    WebView mWebView;
    @BindView(R.id.progress)
    ProgressBar progress;
    private String url;
    private String param;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    break;
                case 1:
                    break;
                case 2:
                    break;
                default:
                    break;
            }
        }

        ;
    };

    private static final int GET_ADDRESS = 0x12;
    private static final int GAODI_ADDRESS = 0x15;
    private static final int SHIPPING_ADDRESS = 0x13;
    private  static final int FILE_CHOOSER_RESULT_CODE = 0x11;
    private  static final int Log_in = 0x16;
    private String loginUrl ;
    private boolean isLoadUrl = false;
    private Tencent mTencent;// 新建Tencent实例用于调用分享方法
    private ShareInformation shareInformation;
    private Bitmap wxBitmap;
    private String address_params = "";
    boolean isbanner = false;
    private ValueCallback<Uri[]> uploadMessageAboveL;
    private ValueCallback<Uri> uploadMessage;
    /** 视频全屏参数 */
    protected static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
    private View customView;
    private FrameLayout fullscreenContainer;
    private WebChromeClient.CustomViewCallback customViewCallback;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rp_activity_web);
        ButterKnife.bind(this);
        progress.setVisibility(View.VISIBLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
                WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
        token = UserInfoUtil.getInfoToken(getApplicationContext());
        mTencent = Tencent.createInstance(QQ_APP_ID, getApplicationContext());

        param = getIntent().getStringExtra(INTENT_EXTRA_BEGIN_URL);
        isbanner = getIntent().getBooleanExtra("isbanner",false);

        url = H5_SERVER_URL + param + "&token=" + token + "&source=app";
        if(!url.contains("latitude")){
            url+="&latitude="+UserInfoUtil.mLatitude+"&longitude="+UserInfoUtil.mLongitude;
        }
        if(isbanner){
            url = param;
        }
        Log.i("1234","url="+url);
        initData();

    }

    public void initData() {
        mWebView.setHorizontalScrollBarEnabled(false);//水平不显示
        mWebView.setVerticalScrollBarEnabled(false); //垂直不显示
        WebSettings webSettings = mWebView.getSettings();


        webSettings.setJavaScriptEnabled(true);
        //支持缩放
        webSettings.setSupportZoom(false);
        //设置缓存模式
        webSettings.setAppCacheEnabled(true);
        webSettings.setDatabaseEnabled(true);
        webSettings.setDomStorageEnabled(true);//开启DOM缓存
        //webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        webSettings.setAppCacheMaxSize(1024*1024*8);
        webSettings.setAppCachePath(mWebView.getContext().getCacheDir().getAbsolutePath());
        //支持插件
        webSettings.setPluginState(WebSettings.PluginState.ON);
        //设置适应屏幕
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        //隐藏原生的缩放控件
        webSettings.setDisplayZoomControls(false);
        //支持内容重新布局
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSettings.supportMultipleWindows();
        webSettings.setSupportMultipleWindows(true);

        //设置可访问文件
        webSettings.setAllowFileAccess(true);
        //当webview调用requestFocus时为webview设置节点
        webSettings.setNeedInitialFocus(true);
        //支持自动加载图片
        if (Build.VERSION.SDK_INT >= 19) {
            webSettings.setLoadsImagesAutomatically(true);
        } else {
            webSettings.setLoadsImagesAutomatically(false);
        }
        webSettings.setNeedInitialFocus(true);
        //设置编码格式
        webSettings.setDefaultTextEncodingName("UTF-8");

      /*  ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if( null != networkInfo && networkInfo.isAvailable()) {
            webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);//网络正常时使用默认缓存策略
        } else {
            webSettings.setCacheMode(WebSettings.LOAD_CACHE_ONLY);//网络不可用时只使用缓存
        }*/

        mWebView.loadUrl(url);
        mWebView.setWebChromeClient(new GoldWebChromeClient());
        mWebView.setWebViewClient(new GoldWebViewClient());
        mWebView.addJavascriptInterface(new JsObject(), "myObject");
        shareInformation();
    }

    @Override
    public void onComplete(Object o) {
        showToast("分享成功");
    }

    @Override
    public void onError(UiError uiError) {
        showToast("分享失败");
    }

    @Override
    public void onCancel() {
        showToast("分享取消");
    }

    @OnClick(R.id.bt_test)
    public void onViewClicked() {

        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.nongzi);
        WXEntryUtil.ShareCaseWebPageToWeixin(getApplicationContext(), bitmap, "粒到农资", "粒到农资", url);
    }

    @Override
    public void onTabActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case FILE_CHOOSER_RESULT_CODE:

                Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
                if (uploadMessageAboveL != null) {
                    onActivityResultAboveL(requestCode, resultCode, data);
                }
                break;
        }
    }


    /***
     * webChromeClient主要是将javascript中相应的方法翻译成android本地方法
     * <p/>
     * 例如：我们重写了onJsAlert方法，那么当页面中需要弹出alert窗口时，便
     * 会执行我们的代码，按照我们的Toast的形式提示用户。
     */
    class GoldWebChromeClient extends WebChromeClient {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            if (newProgress == 100) {
                //mProgress.setVisibility(View.GONE);
                //mProgressBar.setVisibility(View.GONE);
                if(null != progress){
                    progress.setVisibility(View.GONE);
                }
            } else {
                /*if(!mProgress.isShown()){
                    mProgress.setVisibility(View.VISIBLE);
                }
                mProgress.setProgress(newProgress);*/
            }
        }

        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
            //super.onShowFileChooser(webView, filePathCallback, fileChooserParams);
            uploadMessageAboveL = filePathCallback;
            openImageChooserActivity();
            return true;
        }



        public void openFileChooser(ValueCallback<Uri> filePathCallback, String acceptType, String capture) {
            uploadMessage = filePathCallback;
            openImageChooserActivity();
        }

    /*    @Override
        public View getVideoLoadingProgressView() {
            FrameLayout frameLayout = new FrameLayout(WebActivity.this);
            frameLayout.setBackgroundResource(R.color.black);
            frameLayout.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,FrameLayout.LayoutParams.MATCH_PARENT));
            return frameLayout;
        }*/

     /*   @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            //showCustomView(view, callback);
        }

        @Override
        public void onHideCustomView() {
            //hideCustomView();
        }*/


    }


    class GoldWebViewClient extends WebViewClient {

        /*点击页面的某条链接进行跳转的话，会启动系统的默认浏览器进行加载，调出了我们本身的应用
         * 因此，要在shouldOverrideUrlLoading方法中
         */
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, final String url) {
            //使用当前的WebView加载页面
         /*   String[] urlstartsWith = url.split("://");
            String urlStart = urlstartsWith[0];

            if (!urlStart.startsWith("http")) { //私有协议非 HTTP  或者HTTPs
                try {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);   //当协议不是https或者http时就创建一个Intent用来打开对应的客户端app，如果你的手机上没有对应的客户端，第三方的自定义协议就会提供网页版的
                } catch (ActivityNotFoundException e) { //（不过如果没安装的话会报错，代码try catch，是为了保证程序不会崩溃

                }
            } else if (url.contains(".apk")) {
                Intent intent = new Intent();
                intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
                intent.setAction("android.intent.action.VIEW");
                Uri content_url = Uri.parse(url);
                intent.setData(content_url);
                startActivity(intent);
            } else {
                view.loadUrl(url);
            }*/

            view.loadUrl(url);

            return true;
        }


        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            if (!isLoadUrl) {
                isLoadUrl = true;
                view.loadUrl(url);
            }
            super.onPageStarted(view, url, favicon);
        }
    }


    class JsObject {

        @JavascriptInterface
        public void selectLotteryAddress() {  //选择收货地址
            Intent intent = new Intent(getApplicationContext(), AddressActivity.class);
            intent.putExtra("isfromp",false);
            startActivityForResult(intent, SHIPPING_ADDRESS);

        }

        @JavascriptInterface
        public void createBill(String prodInfo) {  //立即购买
            try {
              // TypeToken<QuickOrder> typeToken = new TypeToken<QuickOrder>(){};
                //QuickOrder  result = GsonUtils.fromJson(prodInfo, typeToken);
                Intent intent = new Intent(WebActivity.this, EditOrderFormActivity.class);
                intent.putExtra(KEY_QUICK_ORDER,prodInfo);
                startActivity(intent);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @JavascriptInterface
        public void getCoupon(String coupon) {   //获取优惠券
            Intent intent = new Intent();
            intent.putExtra("coupon", coupon);
            setResult(Activity.RESULT_OK, intent);
            finish();

        }

        @JavascriptInterface
        public void gotoShopCart() {  //进入购物车
            Intent intent = new Intent(getApplicationContext(), ShoppingCartActivity.class);
            intent.putExtra("isShowBackKey",true);
            startActivity(intent);
        }

        @JavascriptInterface
        public void selectAddress(String params) { ////推广商选择省市区
            Log.e("HQQ"," params:  "+params);
            try {
                JSONObject jsonObject = new JSONObject(params);
                address_params = jsonObject.getString("params");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            Intent intent = new Intent(getApplicationContext(), CityListActivity.class);
            startActivityForResult(intent, GET_ADDRESS);
        }

        @JavascriptInterface
        public void shareWX() {  /////分享微信
            if(null != shareInformation){
                WXEntryUtil.ShareCaseWebPageToWeixin(getApplicationContext(), wxBitmap, shareInformation.getShare().getTitle(), shareInformation.getShare().getDesc(), shareInformation.getShare().getLink());
            }
        }

        @JavascriptInterface
        public void shareQQ() {   /////分享qq
            if(null != shareInformation){
                shareToQQ();
            }

        }

        @JavascriptInterface
        public void shareSpace() { ///分享空间
            if(null != shareInformation){
                shareToQZone();
            }

        }

        @JavascriptInterface
        public void shareFriends() { ///分享朋友圈
            WXEntryUtil.ShareCaseWebPageToWeixinFriendGroup(getApplicationContext(), wxBitmap, shareInformation.getShare().getTitle(), shareInformation.getShare().getDesc(),  shareInformation.getShare().getLink());
        }

        @JavascriptInterface
        public void gotoMap(String param) {  ///进入地图显示店铺

            Intent intent = new Intent(getApplicationContext(), BasicMapActivity.class);
            intent.putExtra("param",param);
            startActivityForResult(intent,GAODI_ADDRESS);
        }

        @JavascriptInterface
        public void createBill() {
            Intent intent = new Intent(getApplicationContext(), EditOrderFormActivity.class);
            startActivity(intent);
        }

        @JavascriptInterface
        public void tabbarShow() {
            EventBus.getDefault().post(125);
        }

        @JavascriptInterface
        public void tabbarHidden() {
            EventBus.getDefault().post(126);
        }

        @JavascriptInterface
        public void gotoLogin(String param) {
            Log.e("HQQ","param:"+param);
            try {
                JSONObject jsonObject = new JSONObject(param);
                loginUrl =jsonObject.getString("url");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            UserInfoUtil.saveToken(WebActivity.this,"");

            Intent intent = new Intent(WebActivity.this, LoginActivity.class);
            intent.putExtra("fromH5",true);
            startActivityForResult(intent,Log_in);
        }

        @JavascriptInterface
        public void backApp() {
            finish();
        }
        @JavascriptInterface
        public void callPhone(String phone) {
            try {
                JSONObject jsonObject = new JSONObject(phone);
             String pne=jsonObject.getString("phone");
                 call(pne);
            } catch (JSONException e) {
                e.printStackTrace();
            }


        }


    }

    private  String urlTemp;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
        //super.onActivityResult(requestCode, resultCode, data);
       /* if(resultCode != RESULT_OK ){
            return;
        }*/

        switch (requestCode) {
            case GET_ADDRESS:
                Province.RegionsBean myProvince = (Province.RegionsBean) data.getSerializableExtra("Province");
                Province.RegionsBean myCity = (Province.RegionsBean) data.getSerializableExtra("City");
                Province.RegionsBean myArea = (Province.RegionsBean) data.getSerializableExtra("Area");
                urlTemp = H5_SERVER_URL +"serviceprovider?";
                urlTemp = urlTemp + "&provinceName=" + myProvince.getName() +
                        "&provinceId=" + myProvince.getId()
                        + "&cityName=" + myCity.getName()
                        + "&cityId=" + myCity.getId()
                        + "&countyName=" + myArea.getName()
                        + "&countyId=" + myArea.getId()
                        +"&token=" + token + "&source=app"
                +address_params;


                mHandler.post(new Runnable() {
                    @Override
                    public void run() {

                        mWebView.loadUrl(urlTemp);
                        mWebView.reload(); //刷新
                    }
                });
                break;
            case SHIPPING_ADDRESS:
                Address.AddressesBean.DataBean dataBean = (Address.AddressesBean.DataBean) data.getSerializableExtra("Address");
            final     String newUrl = H5_SERVER_URL+"lotteryresult?userName="+dataBean.getConsignee() +
                        "&phone="+dataBean.getPhone() +
                        "&address="+dataBean.getProvince_name() +dataBean.getCity_name() +dataBean.getCounty_name()+dataBean.getStreet()+
                        "&addressId="+dataBean.getAddress_id()+
                "&token="+token+"&source=app";
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {

                        mWebView.loadUrl(newUrl);
                        mWebView.reload(); //刷新
                    }
                });
                break;
            case Constants.REQUEST_API: //QQ分享
                Tencent.onActivityResultData(requestCode, resultCode, data, this);
                if (resultCode == Constants.REQUEST_QQ_SHARE || resultCode == Constants.REQUEST_QZONE_SHARE || resultCode == Constants.REQUEST_OLD_SHARE) {
                    Tencent.handleResultData(data, this);
                }
                break;
            case  GAODI_ADDRESS:
                break;
            case FILE_CHOOSER_RESULT_CODE:

                Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
                if (uploadMessageAboveL != null) {
                    onActivityResultAboveL(requestCode, resultCode, data);
                }
                break;

            case Log_in:
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                      String[]  temp = loginUrl.split("&source=app");
                        loginUrl =temp[0]+UserInfoUtil.getInfoToken(getApplicationContext()) +"&source=app";
                        mWebView.loadUrl(loginUrl);
                        mWebView.reload(); //刷新
                    }
                });
                break;

        }


    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent intent) {
        if (requestCode != FILE_CHOOSER_RESULT_CODE || uploadMessageAboveL == null)
            return;
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {

            ArrayList<String> selectPath = intent.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
            if(null != selectPath && !selectPath.isEmpty()){
                results = new Uri[]{Uri.fromFile(new File(compressUploadPicture(selectPath.get(0))))};
            }

        }
        uploadMessageAboveL.onReceiveValue(results);
        uploadMessageAboveL = null;
    }

    private Bundle params;

    private void shareToQQ() {
        params = new Bundle();
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
        params.putString(QQShare.SHARE_TO_QQ_TITLE, shareInformation.getShare().getTitle());// 标题
        params.putString(QQShare.SHARE_TO_QQ_SUMMARY,  shareInformation.getShare().getDesc());// 摘要
        params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, shareInformation.getShare().getLink());// 内容地址

        params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, shareInformation.getShare().getIcon());// 网络图片地址　　
        params.putString(QQShare.SHARE_TO_QQ_APP_NAME, getResources().getString(R.string.app_name));// 应用名称
        params.putString(QQShare.SHARE_TO_QQ_EXT_INT, "其它附加功能");
// 分享操作要在主线程中完成
        mTencent.shareToQQ(this, params, this);
    }


    private void shareToQZone() {
        params = new Bundle();
        params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
        params.putString(QzoneShare.SHARE_TO_QQ_TITLE, shareInformation.getShare().getTitle());// 标题
        params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, shareInformation.getShare().getDesc());// 摘要
        params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, shareInformation.getShare().getLink());// 内容地址
        ArrayList<String> imgUrlList = new ArrayList<>();
        imgUrlList.add(shareInformation.getShare().getIcon());
        params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, imgUrlList);// 图片地址
// 分享操作要在主线程中完成
        mTencent.shareToQzone(this, params, this);
    }


    private void shareInformation(){
        String url = API.INVITATION +"&access_token=" + token ;
        HashMap<String,String> header = new HashMap<>();
        header.put("Accept","*/*");

        TypeToken<ShareInformation> typeToken = new TypeToken<ShareInformation>(){};
        OkHttpUtils.get().headers(header).url(url).build().execute(new ObjectCallBack<ShareInformation>(typeToken) {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(ShareInformation response, int id) {
                if(response.getErr_code() == 0){
                    shareInformation = response;
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    wxBitmap = Glide.with(getApplicationContext())
                                            .load(shareInformation.getShare().getIcon())
                                            .asBitmap() //必须
                                            .into(50,50)
                                            .get();
                                    if(wxBitmap == null){
                                        wxBitmap = BitmapFactory.decodeResource(getResources(),R.mipmap.wx_logo);
                                    }
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                } catch (ExecutionException e) {
                                    e.printStackTrace();
                                }
                            }
                        }).start();




                }

            }
        });
    }

    /**
     * 调用拨号功能
     * @param phone 电话号码
     */
    private void call(String phone) {
        Intent intent=new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+phone));
        startActivity(intent);
    }


    @Override
    public void onBackPressed() {
        if (customView != null) {
            hideCustomView();
        } else if (mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            finish();
        }
    }


    private void openImageChooserActivity() {

      /*  Intent intent=new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        getParent().startActivityForResult(intent,FILE_CHOOSER_RESULT_CODE);*/

        Intent intent = new Intent(this, MultiImageSelectorActivity.class);
        // whether show camera
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
        // max select image amount
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 1);
        // select mode (MultiImageSelectorActivity.MODE_SINGLE OR MultiImageSelectorActivity.MODE_MULTI)
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
        if(null != getParent()){
            getParent().startActivityForResult(intent, FILE_CHOOSER_RESULT_CODE);
        }else {
            startActivityForResult(intent, FILE_CHOOSER_RESULT_CODE);
        }

    }

    /** 视频播放全屏 **/
    private void showCustomView(View view, WebChromeClient.CustomViewCallback callback) {
        // if a view already exists then immediately terminate the new one
        if (customView != null) {
            callback.onCustomViewHidden();
            return;
        }

       //getWindow().getDecorView();

        FrameLayout decor = (FrameLayout) getWindow().getDecorView();
        fullscreenContainer = new FullscreenHolder(WebActivity.this);
        fullscreenContainer.addView(view, COVER_SCREEN_PARAMS);
        decor.addView(fullscreenContainer, COVER_SCREEN_PARAMS);
        customView = view;
        setStatusBarVisibility(false);
        customViewCallback = callback;
    }

    /** 全屏容器界面 */
    static class FullscreenHolder extends FrameLayout {

        public FullscreenHolder(Context ctx) {
            super(ctx);
            setBackgroundColor(ctx.getResources().getColor(android.R.color.black));
        }

     /*   @Override
        public boolean onTouchEvent(MotionEvent evt) {
            return true;
        }*/
    }

    private void setStatusBarVisibility(boolean visible) {
        int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
        getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }


    /** 隐藏视频全屏 */
    private void hideCustomView() {
        if (customView == null) {
            return;
        }

        setStatusBarVisibility(true);
        FrameLayout decor = (FrameLayout) getWindow().getDecorView();
        decor.removeView(fullscreenContainer);
        fullscreenContainer = null;
        customView = null;
        customViewCallback.onCustomViewHidden();
        mWebView.setVisibility(View.VISIBLE);
    }

    private String compressUploadPicture(String imagePath) {

        String compressPath = Environment.getExternalStorageDirectory()
                + File.separator + SystemClock.currentThreadTimeMillis() + ".jpg";
        File file = new File(imagePath);
        if (file.exists()) {
            Bitmap bitmap = compressBySize(imagePath, compressBySizeWidth,
                    compressBySizeHeight);
            // 保存图片
            try {
                saveFile(bitmap, compressPath);
            } catch (Exception e) {
                e.printStackTrace();
            }

            return compressPath;
        } else {
            return null;
        }
    }

    // 压缩图片尺寸
    public Bitmap compressBySize(String pathName, int targetWidth,
                                 int targetHeight) {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;// 不去真的解析图片，只是获取图片的头部信息，包含宽高等；
        Bitmap bitmap = BitmapFactory.decodeFile(pathName, opts);
        // 得到图片的宽度、高度；
        float imgWidth = opts.outWidth;
        float imgHeight = opts.outHeight;
        // 分别计算图片宽度、高度与目标宽度、高度的比例；取大于等于该比例的最小整数；
        int widthRatio = (int) Math.ceil(imgWidth / (float) targetWidth);
        int heightRatio = (int) Math.ceil(imgHeight / (float) targetHeight);
        opts.inSampleSize = 1;
        if (widthRatio > 1 || widthRatio > 1) {
            if (widthRatio > heightRatio) {
                opts.inSampleSize = widthRatio;
            } else {
                opts.inSampleSize = heightRatio;
            }
        }
        // 设置好缩放比例后，加载图片进内容；
        opts.inJustDecodeBounds = false;
        bitmap = BitmapFactory.decodeFile(pathName, opts);

        bitmap = rotateBitmapByDegree(bitmap, getImageDegree(pathName));
        return bitmap;
    }


    // 存储进SD卡
    public void saveFile(Bitmap bm, String fileName) throws Exception {
        File dirFile = new File(fileName);
        // 检测图片是否存在
        if (dirFile.exists()) {
            dirFile.delete(); // 删除原图片
        }
        File myCaptureFile = new File(fileName);
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream(myCaptureFile));
        // 100表示不进行压缩，70表示压缩率为30%
        bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
        bos.flush();
        bos.close();
    }

    /**
     * 将图片按照某个角度进行旋转
     *
     * @param bm     需要旋转的图片
     * @param degree 旋转角度
     * @return 旋转后的图片
     */
    public Bitmap rotateBitmapByDegree(Bitmap bm, int degree) {
        Bitmap returnBm = null;

        // 根据旋转角度，生成旋转矩阵
        Matrix matrix = new Matrix();
        matrix.postRotate(degree);
        try {
            // 将原始图片按照旋转矩阵进行旋转，并得到新的图片
            returnBm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
                    bm.getHeight(), matrix, true);
        } catch (OutOfMemoryError e) {
        }
        if (returnBm == null) {
            returnBm = bm;
        }
        if (bm != returnBm) {
            bm.recycle();
        }
        return returnBm;
    }

    private int getImageDegree(String path) {
        int degree = 0;
        try {
            // 从指定路径下读取图片，并获取其EXIF信息
            ExifInterface exifInterface = new ExifInterface(path);
            // 获取图片的旋转信息
            int orientation = exifInterface.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }
}
